/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author EliteBook
 */
public class Especiales extends javax.swing.JDialog {

    /**
     * Creates new form Chip
     */
    DefaultTableModel dtm;
    PrecioCantidad prcd;
    int codigo;
    String icc;
    String tipo;
    Vector especiales;
    Vector especialesId;

    public Especiales(java.awt.Frame parent, boolean modal, PrecioCantidad pr, int id, String t, String ic, Vector es, Vector esi) {
        super(parent, modal);
        initComponents();
        dtm = (DefaultTableModel) jTable1.getModel();
        prcd = pr;
        codigo = id;
        tipo = t;
        icc = ic;
        especiales = es;
        especialesId = esi;
        JTableHeader th = jTable1.getTableHeader();
        TableColumnModel tcm = th.getColumnModel();
        TableColumn tc = tcm.getColumn(1);
        if ("Chip".equals(tipo)) {
            if (icc.equals("")) {
                jLabel1.setText("Selecciona el ICC del chip a vender");
            }
            tc.setHeaderValue("ICC");

        } else {
            tc.setHeaderValue("IMEI");
            jLabel1.setText("Selecciona el IMEI de este Celular");
        }
        th.repaint();
        cargarDatos();
    }

    private void cargarDatos() {
        try {
            prcd.setCantidad(0.0f);
            String andic = (icc.equals("") || codigo == -4) ? "" : "and clave like '%" + icc + "%'";
            PreparedStatement ps = local_connection.cn.prepareStatement("Select especiales.id_producto, clave, productos.nombre, precio from productos join precios on productos.id_producto = precios.id_producto "
                    + "join especiales on especiales.id_producto = productos.id_producto where productos.tipo=? and especiales.sucursal = ? and precios.sucursal=? and (" + ((tipo.equals("Chip")) ? "productos.id_producto = -4 or " : "")
                    + "productos.id_producto = ? " + ((codigo == -4) ? "or productos.tipo='Chip'" : "") + ") and vendido=0 " + andic);
            ps.setString(1, tipo);
            ps.setInt(2, VentanaPrincipal.sucursal);
            ps.setInt(3, VentanaPrincipal.sucursal);
            ps.setInt(4, codigo);
            ResultSet rs = ps.executeQuery();
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                if (!especiales.contains(rows[1])) {
                    data.add(rows);
                }
            }
            for (Object[] data1 : data) {
                dtm.addRow(data1);
            }
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "ICC", "Nombre", "Precio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.String.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setMaxWidth(55);
            jTable1.getColumnModel().getColumn(3).setMaxWidth(55);
        }

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Selecciona el modo de venta para este Chip");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        if (evt.getClickCount() == 2) {
            int row = jTable1.getSelectedRow();
            if (row != -1) {
                row = jTable1.convertRowIndexToModel(row);
                if (tipo.equals("Chip")) {
                    (new ActivarChip(null, true, String.valueOf(dtm.getValueAt(row, 1)))).setVisible(true);
                    if (ActivarChip.activado) {
                        venderEspecial(row);
                    }
                } else {
                    venderEspecial(row);
                }
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked
    private void venderEspecial(int row) {

        prcd.setCantidad(1.0f);
        prcd.setPeso(0);
        prcd.setModo("Unitario");
        prcd.setPrecio(((BigDecimal) dtm.getValueAt(row, 3)).floatValue());
        prcd.setTipo(tipo);
        especiales.add(dtm.getValueAt(row, 1));
        especialesId.add(dtm.getValueAt(row, 0));
        this.dispose();

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
